<?php
/**
 * @abstract All the resources have to be one word
 * 
 */

function DOMinnerHTML($element)
{
    $innerHTML = "";
    $children = $element->childNodes;
    foreach ($children as $child)
    {
        $tmp_dom = new DOMDocument();
        $tmp_dom->appendChild($tmp_dom->importNode($child, true));
        $innerHTML.=trim($tmp_dom->saveHTML());
    }
    return $innerHTML;
} 

class Devel_HttpController extends Clu_Controller_Action_Hvn
{
	/*
    public function getYellowPages()
    {
    
    
    }*/
    

    public function crawlAction()
    {
        // This is actually exactly the same:
        $client = new Zend_Http_Client();
        
        //$client->setUri('http://www.yellowpages.vn/search.php?ids=hn7jgl5i6f4nigk8kklfjbkoe5');
        $client->setUri('http://framework.zend.com/manual/en/zend.dom.html');
        $client->setMethod(Zend_Http_Client::POST);
        //$client->setParameterPost('id', 'tobeposted123');
    
    //    $client->setUri('http://vnexpress.net/GL/Home/');
        $client->setConfig(array(
        	'useragent' => "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1",
            'maxredirects' => 0,
            'timeout'      => 30));
         $response = $client->request();
	    //$response->sendResponse(); die($response);
         /*
          $dom = new Zend_Dom_Query($response);
         $results = $dom->query('.foo .bar a');
		*/
         
      //  	$this->renderToHolder('http/index.phtml');
    }
    public function domAction()
    {
     	
        $url = $this->_request->getParam('url');//"http://vnexpress.net/GL/Xa-hoi/Nhip-dieu-tre/2009/11/3BA15AF2/";
        if (!$url)
        {
        	$a = $this->view->render("commonTheme/commonLang/common/url-form.phtml");
        	die($a);
        }
        //die($url);
        //$url = "'" . $url . "'";
    	$client = new Zend_Http_Client();
        //$url = "http://hvn/en/devel/http/foo-view";
        $wrapperSelector = "div.content";
        $contentSelector = 'div[cpms="true"]'; //includes title
        $titleSelector = "p.Title";
        //$client->setUri('http://www.yellowpages.vn/search.php?ids=hn7jgl5i6f4nigk8kklfjbkoe5');
        //$client->setUri('http://hvn/en/devel/http/foo-view');
        $client->setUri($url);
        $client->setMethod(Zend_Http_Client::GET);
        $response = $client->request();
        //echo $response->getBody();
    	$dom = new Zend_Dom_Query();
    	$dom->setDocumentHtml($response->getBody());
    	//die_a($dom); 
        $titles = $dom->query($titleSelector);
        $title = $titles->current()->nodeValue;
        $viewParams['title'] = $title;

        $contents = $dom->query($wrapperSelector);

        $content = DOMinnerHTML($contents->current());//->nodeValue;
        $viewParams['content'] = $content;
        
//        //die_a($titleResult->getDocument());
//        foreach ($titles as $r) {
//        	echo $r->nodeValue . "<hr/>";
//        }
        
        
//        $varName = "test";
//        $test = "should be gone";
//        echo ${$varName};
        //die();
        $viewParams['cssLinks'] = array("http://vnexpress.net//Resource/Common/default.css");
        $viewParams['base'] = "http://vnexpress.net";
        $viewParams['contentClass'] = "content";
        $this->view->viewParams = $viewParams;
        $a = $this->view->render("commonTheme/commonLang/common/output.phtml");
        die($a);
    }
    
    
    public function fooViewAction()
    {
    	$a = $this->view->render("commonTheme/commonLang/common/vnexpress.phtml");
    	die($a);
    }
    public function postAction()
    {
    	$lang = $this->_request->getParam("language");
//    	die_a($_SERVER);
    	if ($this->_request->isPost())
        {
        	
        	$id = $this->_request->getParam("id");
        	echo "<br/><b>" . "User agent: " . $_SERVER['HTTP_USER_AGENT'] . "<br/>";
        	echo "lang " .$lang . "<br/>";
        	echo "id " . $id . "<br/>";
        	echo "</b>";
        	die();
    	}
    	else 
    		die("not a post");
    }
    
/*
    public function getVillagesAction()
    {
		return;
    	$villageUrl = "http://www.simplevietnam.com/main/ajaxPhuong/";
    	$client = new Zend_Http_Client();
        $client->setConfig(array(
            	'useragent' => "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1",
                'maxredirects' => 0,
                'timeout'      => 30));
        
		$sql = "SELECT district_id FROM districts";
		$ret = $this->db->fetchAll($sql);
		$districtList = array();
		foreach ($ret as $tmp)   
			$districtList[] = $tmp['district_id'];
//			 	
		foreach ($districtList as $dId)
		{
//			$dId = 875;
//			echo $dId."<br/>";
			//insert district
            $client->setUri($villageUrl.$dId);
            $response = $client->request();
            $villageSelect = $response->getBody();
			$villageList = $this->parseVillageSelectList($villageSelect);
			
			foreach ($villageList as $vName)
			{
				$this->insertVillage($dId, $vName);
			}	
		}	
//		die();
    
    }    
*/    
    public function parseVillageSelectList($str)
    {

        $matches = array();
        $pattern = "/value=\"[^\"]*\">/";
        preg_match_all ($pattern, $str, $matches);
//        die_a($matches);
        $villageList = array();
        $search = array('"','>');
        foreach ($matches[0] as $v)
        {
        	$villageList[] = str_replace($search, '',substr(trim($v),7)); 
        }
//        die_a($villageList);
return $villageList;
        
	}    			    
    /*
    public function geoAction()
    {
    	$cities = array(
        	"168"=>"An Giang",
    		"259"=>"Bà Rịa-Vũng Tàu",
    		"256"=>"Bình Dương",
    		"257"=>"Bình Phước",
    		"215"=>"Bình Thuận",
    		"226"=>"Bình Định",
            "262"=>"Bạc Liêu",
            "208"=>"Bắc Giang",
            "190"=>"Bắc Kạn",
            "182"=>"Bắc Ninh",
            "356"=>"Bến Tre",
            "158"=>"Cao Bằng",
            "178"=>"Cà Mau",
            "173"=>"Cần Thơ",
            "224"=>"Gia Lai",
            "189"=>"Hà Giang",
            "185"=>"Hà Nam",
            "20"=>"Hà Nội",
            "210"=>"Hà Tĩnh",
            "204"=>"Hòa Bình",
            "181"=>"Hưng Yên",
            "180"=>"Hải Dương",
            "163"=>"Hải Phòng",
            "174"=>"Hậu Giang",
            "34"=>"Hồ Chí Minh",
            "218"=>"Khánh Hòa",
            "172"=>"Kiên Giang",
            "225"=>"Kon Tum",
            "159"=>"Lai Châu",
            "255"=>"Long An",
            "157"=>"Lào Cai",
            "221"=>"Lâm Đồng",
            "156"=>"Lạng Sơn",
            "186"=>"Nam Định",
            "213"=>"Nghệ An",
            "188"=>"Ninh Bình",
            "227"=>"Ninh Thuận",
            "194"=>"Phú Thọ",
            "217"=>"Phú Yên",
            "211"=>"Quảng Bình",
            "228"=>"Quảng Nam",
            "220"=>"Quảng Ngãi",
            "200"=>"Quảng Ninh",
            "212"=>"Quảng Trị",
            "176"=>"Sóc Trăng",
            "203"=>"Sơn La",
            "376"=>"Thanh Hóa",
            "187"=>"Thái Bình",
            "193"=>"Thái Nguyên",
            "30"=>"Thừa Thiên - Huế",
            "169"=>"Tiền Giang",
            "261"=>"Trà Vinh",
            "191"=>"Tuyên Quang",
            "253"=>"Tây Ninh",
            "263"=>"Vĩnh Long",
            "195"=>"Vĩnh Phúc",
            "192"=>"Yên Bái",
            "202"=>"Điện Biên",
            "29"=>"Đà Nẵng",
            "223"=>"Đắk Lắk",
            "222"=>"Đắk Nông",
            "260"=>"Đồng Nai",
            "258"=>"Đồng Tháp");
    	
    	$districtUrl = "http://www.simplevietnam.com/main/ajaxQuan/";
    	$villageUrl = "http://www.simplevietnam.com/main/ajaxPhuong/";
    	$client = new Zend_Http_Client();
        $client->setConfig(array(
            	'useragent' => "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1",
                'maxredirects' => 0,
                'timeout'      => 30));
    	
    	foreach ($cities as $cityId=>$cityName)
    	{
    		//insert the City
//    		$cityId = "168";
//    		$cityName = "An Giang";
    		$this->insertCity($cityId, $cityName, "Vietnam");
    		
    		//insert districts
            $client->setUri($districtUrl.$cityId);
            $response = $client->request();
            $districtSelect = $response->getBody();
			$districtList = $this->parseSelectList($districtSelect);
			foreach ($districtList as $dId => $dName)
			{
				//insert district
				$this->insertDistrict($cityId, $dId, $dName);
				//insert vilages
                $client->setUri($villageUrl.$dId);
                $response = $client->request();
                $villageSelect = $response->getBody();
    			$villageList = $this->parseSelectList($villageSelect);
				foreach ($villageSelect as $vId => $vName)
				{
					$this->insertVillage($dId, $vId, $vName);
				}	
			}	
    	}
    
    }
*/
    
    public function parseSelectList($str)
    {
//        $str = <<<EOD
//            Quận / Huyện:[.^.]<select id="quan" name="quan" onChange="doQuan()" style="width:150px;">
//            <option value="-" selected="selected">Tất cả</option>
//            <option value="875">An Phú</option>
//            <option value="876">Châu Đốc</option>
//            <option value="877">Châu Phú</option>
//            <option value="878">Châu Thành</option>
//            <option value="879">Chợ Mới</option>
//            <option value="880">Long Xuyên</option>
//            <option value="11803">Phú Lộc</option>
//            
//            <option value="881">Phú Tân</option>
//            <option value="11759">Sầm Sơn</option>
//            <option value="882">Tân Châu</option>
//            <option value="883">Thoại Sơn</option>
//            <option value="884">Tịnh Biên</option>
//            <option value="885">Tri Tôn</option>
//            </select>
//            EOD;
        $matches = array();
        $pattern = "/\"\d+\">[^<]*/";
        preg_match_all ($pattern, $str, $matches);
        $districtList = array();
        foreach ($matches[0] as $v)
        {
        	preg_match("/\d+/", $v, $districtId);
        	preg_match("/>(.)*$/", $v, $districtName);
        	$districtList[$districtId[0]] = substr(trim($districtName[0]),1); 
        }
        /*
        Array
            (
                [875] => An Phú
                [876] => Châu Đốc
                [877] => Châu Phú
                [878] => Châu Thành
                [879] => Chợ Mới
                [880] => Long Xuyên
                [11803] => Phú Lộc
                [881] => Phú Tân
                [11759] => Sầm Sơn
                [882] => Tân Châu
                [883] => Thoại Sơn
                [884] => Tịnh Biên
                [885] => Tri Tôn
            )
        */
		return $districtList;
	}    		


	public function insertCity($cityId, $cityName, $country)
	{
    	$sql = sprintf("INSERT INTO cities (city_id, city_name, country) VALUES(%d,%s,%s);",$cityId, $this->db->quote($cityName,'STRING'),  $this->db->quote($country,'STRING'));
//    	die($sql);
    	$this->db->query($sql);
	
	}
	
	public function insertDistrict($cityId, $districtId, $districtName)
	{
    	$sql = sprintf("INSERT INTO districts (city_id, district_id, district_name) VALUES(%d,%d,%s);",$cityId, $districtId,  $this->db->quote($districtName,'STRING'));
    	$this->db->query($sql);
	
	}

	public function insertVillage($dId, $vName)
	{
    	$sql = sprintf("INSERT INTO villages (district_id, village_name) VALUES(%d,%s);",$dId, $this->db->quote($vName,'STRING'));
    	$this->db->query($sql);
	}
	
	public function clearTableAction()
	{
        $sql = "DROP TABLE IF EXISTS `cities`;  DROP TABLE IF EXISTS `districts`;  DROP TABLE IF EXISTS `villages`;";
        $this->db->query($sql);
//        die("<a href='http://hvn/en/user/http/create-table'> now create </a>");
	}

    public function createTableAction()
	{
		$this->clearTableAction();
        $sql = "
CREATE TABLE IF NOT EXISTS `cities` (
  `city_id` int(11) NOT NULL,
  `city_name` varchar(80) NOT NULL default '',
  `country` varchar(32) character set utf8 collate utf8_unicode_ci NOT NULL default 'Vietnam',
  KEY `idx_city_name` (`city_name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


CREATE TABLE IF NOT EXISTS `districts` (
  `district_id` int(11) NOT NULL,
  `city_id` int(11) NOT NULL default '0',
  `district_name` varchar(80) NOT NULL default '',
  `longitude` float NOT NULL default '0',
  `latitude` float NOT NULL default '0',
  KEY `idx_district_name` (`district_name`),
  KEY `city_id` (`city_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;


CREATE TABLE IF NOT EXISTS `villages` (
  `village_id` int(11) NOT NULL,
  `district_id` int(11) NOT NULL default '0',
  `village_name` varchar(80) NULL default ' ',
  `longitude` float NOT NULL default '0',
  `latitude` float NOT NULL default '0',
  KEY `idx_village_name` (`village_name`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8";
        
        $this->db->query($sql);
        
        die("<a href='http://hvn/en/user/http/geo'> now get data</a>");
        
	}
	
	//migrating data from villages_backup to villages to create a new
	//village_id become a PRIMARY KEY
	public function migrateDbAction()
	{
		return;
		$sql = "SELECT * FROM villages_backup";
		$rowSet = $this->db->fetchAll($sql);
		foreach ($rowSet as $row)
		{
			$sql = sprintf("INSERT INTO villages (district_id, village_name) VALUES(%d,%s)", $this->db->quote($row['district_id'],'INTEGER'),$this->db->quote($row['village_name'],'STRING'));
			try
			{
				$this->db->query($sql);
			}
			catch (Exception $e)
			{
				//Zend_Registry::get('logger')->log('migrate: duplicate '. $row['village_name'], Zend_Log::INFO);
			}		
		}
		//die_a($rowSet);
		die_a("success");
	}
	
	public function rteAction()
	{
		$a = $this->view->render("commonTheme/commonLang/common/jquery.rte.phtml");
		die($a);
	}
	
}    